package com.ljx.rpc.core.handler;

import com.ljx.rpc.core.domain.dto.RpcRequest;
import com.ljx.rpc.core.domain.dto.RpcResponse;
import com.ljx.rpc.core.exception.RpcException;
import com.ljx.rpc.core.provider.ServiceProvider;
import com.ljx.rpc.core.provider.impl.ServiceProviderImpl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;


/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-10-07  20:15
 */
public class RequestHandler {
    private static ServiceProvider serviceProvider;

    static {
        serviceProvider = new ServiceProviderImpl();
    }

    public Object handle(RpcRequest rpcRequest){
        if (Objects.isNull(rpcRequest.getInterfaceName())){
            throw new RpcException("服务名不能为空");
        }
        Object service = serviceProvider.getService(rpcRequest.getInterfaceName());

        return tryToHandleMethod(service, rpcRequest);

    }

    private Object tryToHandleMethod(Object service, RpcRequest rpcRequest) {
        try {
            Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
            Object result = method.invoke(service, rpcRequest.getParameters());
            return RpcResponse.success(result, "123");
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
}
